<template>
  <div class="data-fusion">
    <h2>数据融合平台</h2>
    <el-row :gutter="20">
      <el-col :span="8">
        <el-card>
          <h3>1. 设备数据</h3>
          <el-table :data="deviceList" style="width: 100%" size="mini">
            <el-table-column prop="deviceId" label="设备ID" width="100"/>
            <el-table-column prop="name" label="设备名称"/>
            <el-table-column prop="status" label="状态"/>
          </el-table>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card>
          <h3>2. 业务数据</h3>
          <el-table :data="businessList" style="width: 100%" size="mini">
            <el-table-column prop="orderId" label="工单编号" width="100"/>
            <el-table-column prop="deviceId" label="设备ID" width="100"/>
            <el-table-column prop="timestamp" label="时间戳" width="160"/>
            <el-table-column prop="scene" label="生产场景"/>
          </el-table>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card>
          <h3>3. 非结构化数据</h3>
          <el-table :data="unstructuredList" style="width: 100%" size="mini">
            <el-table-column prop="deviceId" label="设备ID" width="100"/>
            <el-table-column prop="experience" label="维修经验"/>
            <el-table-column prop="timestamp" label="时间戳" width="160"/>
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <el-divider/>

    <el-card>
      <h3>4. 配置融合规则</h3>
      <el-form :inline="true" :model="fusionRule" size="small">
        <el-form-item label="设备ID">
          <el-select v-model="fusionRule.deviceId" placeholder="选择设备">
            <el-option v-for="d in deviceList" :key="d.deviceId" :label="d.deviceId" :value="d.deviceId"/>
          </el-select>
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="fusionRule.timeRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            align="right"
            :picker-options="pickerOptions"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleFusion">执行融合</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-divider/>

    <el-card>
      <h3>5. 融合结果与质量报告</h3>
      <el-table :data="fusionResults" style="width: 100%" size="mini" @row-click="handleRowClick">
        <el-table-column prop="deviceId" label="设备ID" width="100"/>
        <el-table-column prop="orderId" label="工单编号" width="100"/>
        <el-table-column prop="scene" label="生产场景"/>
        <el-table-column prop="experience" label="维修经验"/>
        <el-table-column prop="status" label="设备状态"/>
        <el-table-column prop="timestamp" label="时间戳" width="160"/>
        <el-table-column prop="quality" label="质量报告"/>
      </el-table>
      <div v-if="fusionResults.length === 0" style="color: #999; margin-top: 10px;">暂无融合结果</div>
    </el-card>

    <el-dialog :visible.sync="showDetail" title="原始数据详情" width="600px">
      <div v-if="detailData">
        <pre>{{ JSON.stringify(detailData, null, 2) }}</pre>
      </div>
    </el-dialog>

    <el-divider/>

    <el-card>
      <h3>6. 关联图谱（简化版）</h3>
      <el-tree
        :data="graphData"
        :props="treeProps"
        node-key="id"
        highlight-current
        default-expand-all
        @node-click="handleTreeNodeClick"
      />
    </el-card>
  </div>
</template>

<script>
import { Message } from 'element-ui'

const LOCAL_KEY = 'fusion_data_v1'

export default {
  name: 'DataFusion',
  data() {
    return {
      deviceList: [],
      businessList: [],
      unstructuredList: [],
      fusionRule: {
        deviceId: '',
        timeRange: []
      },
      fusionResults: [],
      showDetail: false,
      detailData: null,
      graphData: [],
      treeProps: {
        children: 'children',
        label: 'label'
      },
      pickerOptions: {
        disabledDate: () => false
      }
    }
  },
  created() {
    this.initMockData()
    this.loadFusionResults()
    this.buildGraphData()
  },
  methods: {
    // 初始化mock数据
    initMockData() {
      // 设备
      this.deviceList = [
        { deviceId: 'D001', name: '温度传感器', status: '正常' },
        { deviceId: 'D002', name: '压力传感器', status: '异常' },
        { deviceId: 'D003', name: '流量计', status: '正常' }
      ]
      // 业务
      this.businessList = [
        { orderId: 'O1001', deviceId: 'D001', timestamp: '2024-06-01 10:00:00', scene: '生产A' },
        { orderId: 'O1002', deviceId: 'D002', timestamp: '2024-06-01 11:00:00', scene: '生产B' },
        { orderId: 'O1003', deviceId: 'D001', timestamp: '2024-06-01 12:00:00', scene: '生产A' }
      ]
      // 非结构化
      this.unstructuredList = [
        { deviceId: 'D001', experience: '更换传感器探头', timestamp: '2024-06-01 09:50:00' },
        { deviceId: 'D002', experience: '校准压力表', timestamp: '2024-06-01 10:50:00' },
        { deviceId: 'D001', experience: '检查线路', timestamp: '2024-06-01 12:10:00' }
      ]
    },
    // 执行融合
    handleFusion() {
      const { deviceId, timeRange } = this.fusionRule
      if (!deviceId || !timeRange || timeRange.length !== 2) {
        Message.warning('请完整选择设备和时间范围')
        return
      }
      // 过滤业务和非结构化数据
      const [start, end] = timeRange.map(t => new Date(t).getTime())
      const business = this.businessList.filter(
        b => b.deviceId === deviceId && this.inTimeRange(b.timestamp, start, end)
      )
      const unstructured = this.unstructuredList.filter(
        u => u.deviceId === deviceId && this.inTimeRange(u.timestamp, start, end)
      )
      const device = this.deviceList.find(d => d.deviceId === deviceId)
      // 融合
      let results = []
      business.forEach(biz => {
        // 找到时间最近的维修经验
        let exp = unstructured
          .filter(u => Math.abs(new Date(u.timestamp).getTime() - new Date(biz.timestamp).getTime()) < 3600 * 1000)
          .sort((a, b) => Math.abs(new Date(a.timestamp).getTime() - new Date(biz.timestamp).getTime()) -
                          Math.abs(new Date(b.timestamp).getTime() - new Date(biz.timestamp).getTime()))
        let expItem = exp.length > 0 ? exp[0] : null
        // 校验
        let quality = this.checkQuality(device, biz, expItem)
        results.push({
          deviceId,
          orderId: biz.orderId,
          scene: biz.scene,
          experience: expItem ? expItem.experience : '无',
          status: device ? device.status : '未知',
          timestamp: biz.timestamp,
          quality
        })
      })
      // 保存到本地
      this.fusionResults = results
      localStorage.setItem(LOCAL_KEY, JSON.stringify(results))
      this.buildGraphData()
      Message.success('融合完成，已生成质量报告')
    },
    // 时间范围判断
    inTimeRange(ts, start, end) {
      const t = new Date(ts).getTime()
      return t >= start && t <= end
    },
    // 质量校验
    checkQuality(device, biz, exp) {
      let quality = []
      if (!device) quality.push('设备信息缺失')
      if (!biz) quality.push('业务信息缺失')
      if (!exp) quality.push('无维修经验')
      if (biz && exp) {
        // 时间差校验
        const diff = Math.abs(new Date(biz.timestamp).getTime() - new Date(exp.timestamp).getTime())
        if (diff > 3600 * 1000) quality.push('维修经验与业务时间不一致')
      }
      if (quality.length === 0) return '合格'
      return quality.join('，')
    },
    // 加载本地融合结果
    loadFusionResults() {
      const data = localStorage.getItem(LOCAL_KEY)
      if (data) {
        this.fusionResults = JSON.parse(data)
      }
    },
    // 关联图谱
    buildGraphData() {
      // 以设备为根，业务为分支，维修经验为叶
      let data = this.deviceList.map(device => {
        let children = this.businessList
          .filter(biz => biz.deviceId === device.deviceId)
          .map(biz => {
            let exp = this.unstructuredList
              .filter(u => u.deviceId === device.deviceId)
              .map(u => ({
                id: `${device.deviceId}-${biz.orderId}-${u.timestamp}`,
                label: `经验: ${u.experience} (${u.timestamp})`,
                raw: u
              }))
            return {
              id: `${device.deviceId}-${biz.orderId}`,
              label: `工单: ${biz.orderId} (${biz.scene})`,
              children: exp,
              raw: biz
            }
          })
        return {
          id: device.deviceId,
          label: `设备: ${device.deviceId} (${device.name})`,
          children,
          raw: device
        }
      })
      this.graphData = data
    },
    // 下钻详情
    handleRowClick(row) {
      this.detailData = row
      this.showDetail = true
    },
    handleTreeNodeClick(node) {
      if (node.raw) {
        this.detailData = node.raw
        this.showDetail = true
      }
    }
  }
}
</script>

<style scoped>
.data-fusion {
  padding: 20px;
}
.el-card {
  margin-bottom: 20px;
}
</style>
